package d_inject;

/*
  登陆案例:
    1.通过控制台输入用户名何密码
    2.判断用户是否登陆成功  -> 控制台输入何数据库中的对比
    3.获取数据库中的账号和密码

*/

import a_entity.User;
import d_inject.JDBCUtils;

import java.sql.*;
import java.util.Scanner;

public class LoginDemo4 {
    public static void main(String[] args) {
        //1.通过控制台输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入账号");
        String username = scanner.nextLine();
        System.out.println("请输入密码");
        String password = scanner.nextLine();
        //2.调用登陆的方法
        LoginDemo4 ld = new LoginDemo4();
        User user = ld.login(username,password);
        if(username.equals(user.getUsername()) && password.equals(user.getPassword())){
            System.out.println(username+"欢迎你!您的序号为"+user.getId());
        }else {
            System.out.println("请输入账号或者密码错误");
        }
    }

    //登陆的方法
    public User login(String username,String password){
        Connection conn = null;
        //Statement sta = null;
        PreparedStatement ps =null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            /**  where username = ? and password = ?   */
            String sql ="select * from user where username =?and password =?";
            /**
             PreparedStatement类
             */
            ps = conn.prepareStatement(sql);
            /** 对?进行赋值操作 */
            ps.setString(1,username);
            ps.setString(2,password);
            //执行sql
            rs = ps.executeQuery(sql);

            while (rs.next()){
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                return user;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
